<?php if( ! defined('BASEPATH')) exit('No direct script access allowed');
/********************
 *@param function:OplusCms 後臺系統管理的數據庫備份
 *@param datetime 2012-01-07
 *@param author solgh
 ********************/
class Backup extends Admins_Controller {
  
  private $data=array();
  private $language_id;
  public function __construct(){
    parent::__construct();
    $this->data['currentPage']='systems';
    $this->data['format_time']=$this->settings['default_time'];
  }
  public function index()
  {
    $this->data['lists']=$this->file_reder();
    $this->load->view('admins/backup_list_view',$this->data);
  }
  
  //執行備份.
  public function add($format='txt'){
    header("Content-Type: text/plain; charset=UTF-8");
    
    $this->load->dbutil();
     
    $this->load->helper('file');
    $nick_name=$this->nsession->userdata('nick_name');
    $filename=time().'_'.$nick_name.'.sql';
    $prefs = array(
                'ignore'      => array(),           // 备份时需要被忽略的表
                'format'      => $format,             // gzip, zip, txt
                'filename'    => $filename,    // 文件名 - 如果选择了ZIP压缩,此项就是必需的
                'add_drop'    => TRUE,              // 是否要在备份文件中添加 DROP TABLE 语句
                'add_insert'  => TRUE,              // 是否要在备份文件中添加 INSERT 语句
                'newline'     => "\n"               // 备份文件中的换行符
              );
    $backup = $this->dbutil->backup($prefs);
    $result=write_file('backup/'.$filename.'', $backup); 
    
    $this->operator_log('備份數據庫:'.$filename,'備份',$result);
    $msg = $result > 0?'恭喜,您的操作成功!':'對不起,您的操作失敗';
    $notify = $result > 0?'success':'error';
    $this->nsession->set_flashdata($notify, $msg);
    redirect("admins/backup");
  }
  
  //遍歷備份文件夾
  private function file_reder(){
     $dir=FCPATH."backup/"; //備份路徑
     if(file_exists($dir)){
       $handle=opendir($dir.".");
       $data=array(); 
       while (false !== ($file = readdir($handle))) 
        { 
            if ($file != "." && $file != "..") { 
              $file_name=basename($file,".sql");
              $file_arr=explode('_',$file_name);
              $data[]=array(
                'filename'=>$file,
                'add_time'=>$file_arr[0],
                'author'=>$file_arr[1],
              );
            } 
        }
        return $this->array_sort($data,'add_time');
    }else{
      Imagelib::mkdir_file($dir); //創建路徑
    }
  }
  
  //數組排序一下.
  private function array_sort($multi_array,$sort_key,$sort=SORT_DESC){
    if(is_array($multi_array) && count($multi_array)>0){
      foreach ($multi_array as $row_array){
        if(is_array($row_array)){
          $key_array[] = $row_array[$sort_key];
        }else{
          return false;
        }
      }
    }else{
      return false;
    }
    array_multisort($key_array,$sort,$multi_array);
    return $multi_array;
  }
  
  //還原數據庫功能
  public function reduction($filename=''){
    if(!empty($filename)){
      $dir="backup/"; //備份路徑
      $result=0;
      if(file_exists($file_path = APPPATH.'config/database.php')){
        require($file_path);
        $conn = mysql_connect($db['default']['hostname'],$db['default']['username'],$db['default']['password']);
        mysql_select_db($db['default']['database']);
        mysql_query("set names 'utf8'");
        $this->load->helper('file');
        $content = read_file($dir.$filename);
        $content = preg_replace("/#(.*)\s#(.*)TABLE(.*)(.*)\s#/i","",$content);//去掉注释部分
        $sqls = explode(";\n",$content);
        foreach($sqls as $sql){
            if(str_replace(" ","",$sql)){
              $result+=mysql_query(trim($sql)) or die(mysql_error());
            }
        }
        mysql_close($conn);
      }
      $msg = $result > 0?'恭喜,您的操作成功!':'對不起,您的操作失敗';
      $notify = $result > 0?'success':'error';
      $this->nsession->set_flashdata($notify, $msg);
      redirect("admins/backup");
    }else{
      show_error('對不起,參數出錯');
      exit;
    }
  }
  
  //下載數據庫
  public function download($filename=''){
    if(!empty($filename)){
      header("Content-Type: text/plain; charset=UTF-8");
      $this->load->helper('download');
      $this->operator_log('下載備份數據庫:'.$filename,'下載',1);
      $data = file_get_contents('backup/'.$filename); // 读文件内容
      $name = $filename;
      force_download($name, $data); 
    }else{
      show_error('對不起,參數出錯');
      exit;
    }
  }
  
  //刪除備份文件
  public function delete($filename=''){
    if(!empty($filename)){
      $result='';
      if(file_exists('backup/'.$filename)){
        $result=@unlink('backup/'.$filename);
        $this->operator_log('刪除備份數據庫:'.$filename,'刪除',1);
      }
      $msg = $result > 0?'恭喜,您的操作成功!':'對不起,您的操作失敗';
      $notify = $result > 0?'success':'error';
      $this->nsession->set_flashdata($notify, $msg);
      redirect("admins/backup");  
    }else{
      show_error('對不起,參數出錯');
      exit;
    }
  }
}